package com.sky.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorsMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.poi.ss.util.CellUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorsMapper flavorsMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品及其口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional //事务注解 统一事务的原子性
    public void addWithFlavors(DishDTO dishDTO) {

        //新增菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        Long id = dish.getId();
        //新增口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollUtil.isEmpty(flavors)) {
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });
            flavorsMapper.addFlavors(flavors);
        }

        String key = "dish_" + dishDTO.getId();
        clearRedis(key);
    }

    /**
     * 分页查询菜品信息
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOPage = dishMapper.page(dishPageQueryDTO);
        PageResult pageResult = new PageResult(dishVOPage.getTotal(), dishVOPage.getResult());
        return pageResult;
    }

    /**
     * 删除菜品信息及其口味
     *
     * @param ids
     */
    @Transactional
    @Override
    public void del(List<Long> ids) {
        //判断当前菜品是否起售中
        for (Long id : ids) {
            DishVO dishVO = dishMapper.selectByDishId(id);
            if (dishVO.getStatus() == StatusConstant.ENABLE)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断当前菜品是否包含了套餐
        List<Long> setmealIds = setmealDishMapper.selectByDishId(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //批量删除菜品
        dishMapper.deleteByIds(ids);
        //删除口味
        flavorsMapper.deleteByDishIds(ids);
        //清除缓存
        clearRedis("dish_*");
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //获取dishVO对象
        DishVO dishVO = dishMapper.selectByDishId(id);

        List<DishFlavor> dishFlavorList = flavorsMapper.selectByDishId(id);

        dishVO.setFlavors(dishFlavorList);

        return dishVO;
    }

    /**
     * 修改菜单信息
     *
     * @param dishDTO
     */
    @Override
    public void updateWithFlavors(DishDTO dishDTO) {
        //修改菜单信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //清空口味信息
        Long id = dishDTO.getId();
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        flavorsMapper.deleteByDishIds(ids);
        //修改口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });
            flavorsMapper.addFlavors(flavors);
        }
        clearRedis(RedisConstant.DISH_KEY + "*");
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
        clearRedis(RedisConstant.DISH_KEY + "*");
    }

    /**
     * 根据分类id查询菜单
     *
     * @param categoryId
     * @return
     */

    @Override
    public List<DishVO> list(Long categoryId) {
        //获取KEY
        String key = RedisConstant.DISH_KEY + categoryId;
        //从缓存中获取数据
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //存在 直接返回
        if (list != null && list.size() > 0) {
            return list;
        }
        //不存在 查询数据库
        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);

        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setFlavors(flavorsMapper.selectByDishId(dish.getId()));
            dishVOList.add(dishVO);
        }
        //将数据存入缓存
        redisTemplate.opsForValue().set(key, list, RedisConstant.DISH_TIME, TimeUnit.MINUTES);
        return dishVOList;
    }

    /**
     * 清理缓存数据
     */
    private void clearRedis(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
